package com.teragadgets.android.comic;

import java.util.Collections;
import java.util.Observable;
import java.util.Vector;

import android.content.Context;
import android.content.DialogInterface.OnClickListener;

import com.teragadgets.android.comic.datamodel.WebComic;
import com.teragadgets.android.comic.datamodel.WebComicDatabase;
import com.teragadgets.android.comic.feed.WebComicFeedParser;

class WebComicListModel extends Observable {

	private Vector<WebComic> webComics = new Vector<WebComic>();

	public WebComicListModel(Context ctx) {
		updateWebComics(ctx);
	}

	public Vector<WebComic> getWebComics() {
		return webComics;
	}

	@SuppressWarnings("unchecked")
	public void updateWebComics(Context ctx) {
		WebComicDatabase db = WebComicDatabase.open(ctx);
		try {
			Vector<WebComic> newComics = new WebComicFeedParser(
					"http://andcomicsengine.appspot.com/index.jsp?ids="
							+ db.getAllIDs()).getWebComics();
			for (WebComic c : newComics) {
				System.out.println("Updating " + c.getName() + ": "
						+ (db.updateFromAppEngine(c) ? "Success" : "Fail"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		webComics.removeAllElements();
		webComics.addAll(db.fetchAllComics());
		Collections.sort(webComics);
		db.close();

		this.setChanged();
		this.notifyObservers();
	}

	public void save(Context ctx, WebComic webComic, int order) {
		WebComicDatabase db = WebComicDatabase.open(ctx);
		db.updateOrder(webComic.getID(), order);
		db.close();
	}
}